package org.opens.service.impl;

import org.opens.dao.RedisCacheMapper;
import org.opens.entity.RedisCacheEntity;
import org.opens.entity.RedisCacheSaveDTO;
import org.opens.entity.RedisCacheUpdateDTO;
import org.opens.service.RedisCacheService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * redis缓存操做实现类
 *
 * @author zym
 * @Date 2022/6/28 15:35
 */
@Service(value = "redisCacheService")
public class RedisCacheServiceImpl implements RedisCacheService {

    @Autowired
    private RedisCacheMapper redisCacheMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    @Override
    public RedisCacheEntity save(RedisCacheSaveDTO redisCacheSaveDTO) {
        if (redisCacheSaveDTO == null) {
            throw new RuntimeException("操做对象不能为空!");
        }

        RedisCacheEntity entity = new RedisCacheEntity();
        BeanUtils.copyProperties(redisCacheSaveDTO, entity);
        redisCacheMapper.insert(entity);

        return redisCacheMapper.selectById(entity.getId());
    }

    @Override
    public boolean delete(Integer id) {
        RedisCacheEntity entity = redisCacheMapper.selectById(id);
        // 如果已经查不到这个对象, 则表示已经被删掉了, 这里处理为删除成功, 也可以抛出异常
        if (entity == null) {
            return true;
        }

        int affectedRowsNum = redisCacheMapper.deleteById(id);
        return affectedRowsNum == 1;
    }

    @Override
    public RedisCacheEntity update(RedisCacheUpdateDTO redisCacheUpdateDTO) {
        if (redisCacheUpdateDTO == null) {
            throw new RuntimeException("操做对象不能为空!");
        }

        RedisCacheEntity entity = new RedisCacheEntity();
        BeanUtils.copyProperties(redisCacheUpdateDTO, entity);
        redisCacheMapper.updateById(entity);

        return redisCacheMapper.selectById(entity.getId());
    }

    @Override
    public RedisCacheEntity selectById(Integer id) {
        return redisCacheMapper.selectById(id);
    }

}
